from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django_user_agents.utils import get_user_agent
from .models import Antique
from django.core.paginator import Paginator

# Create your views here.

def is_mobile(request):
    user_agent = get_user_agent(request)
    return user_agent.is_mobile or user_agent.is_tablet

def list(request):
    if is_mobile(request):
        return HttpResponseRedirect('/mobile/')
    antiques_list = Antique.objects.all().order_by('order')
    paginator = Paginator(antiques_list, 15)  # 每页15个
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'antiques/list.html', {'antiques': page_obj, 'page_obj': page_obj})

def detail(request, pk):
    if is_mobile(request):
        return HttpResponseRedirect(f'/mobile/{pk}/')
    antique = get_object_or_404(Antique, pk=pk)
    return render(request, 'antiques/detail.html', {'antique': antique})

def mobile_list(request):
    antiques = Antique.objects.all()
    return render(request, 'antiques/mobile/list.html', {'antiques': antiques})

def mobile_detail(request, pk):
    antique = get_object_or_404(Antique, pk=pk)
    return render(request, 'antiques/mobile/detail.html', {'antique': antique})
